package cn.bugDance.trigger.http;

import cn.bugDance.api.security.controller.ILoginController;
import cn.bugDance.domain.security.servive.IWeiXinLoginService;
import cn.bugDance.types.enums.ResponseCode;
import cn.bugDance.types.exception.AppException;
import cn.bugDance.types.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController()
@RequestMapping("/raffle/${app.config.api-version}/login")
@CrossOrigin("${app.config.cross-origin}")
@Slf4j
public class LoginController implements ILoginController {


    @Resource
    private IWeiXinLoginService weiXinLoginService;

    @Override
    @RequestMapping(value = "/get_qrcode_ticket", method = RequestMethod.GET)
    public Response<String> getQrCodeTicket() {
        try{
            String ticket = weiXinLoginService.createQrCodeTicket();
            return Response.<String>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(ticket).build();
        }catch (AppException e){
            return Response.<String>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .data(null).build();
        }catch (Exception e){
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data(null).build();
        }
    }

    @RequestMapping(value = "/check_login", method = RequestMethod.GET)
    public Response<String> checkLogin(@RequestParam String ticket) {
        try {
            String jwtToken = weiXinLoginService.checkJwtToken(ticket);
            log.info("扫描检测登录结果 ticket:{} jwtToken:{}", ticket, jwtToken);
            if (StringUtils.isNotBlank(jwtToken)) {
                return Response.<String>builder()
                        .code(ResponseCode.SUCCESS.getCode())
                        .info(ResponseCode.SUCCESS.getInfo())
                        .data(jwtToken)
                        .build();
            } else {
                return Response.<String>builder()
                        .code(ResponseCode.NO_LOGIN.getCode())
                        .info(ResponseCode.NO_LOGIN.getInfo())
                        .build();
            }
        } catch (Exception e) {
            log.info("扫描检测登录结果失败 ticket:{}", ticket);
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }
}
